package com.chj.comp.service.demo1.controller;

import com.alibaba.fastjson.JSONObject;
import com.chj.comp.common.cache.util.RedisUtil;
import com.chj.comp.service.demo1.entity.Demo1SchedulerJob;
import com.chj.comp.service.demo1.service.IDemo1SchedulerJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cuihui
 * @since 2022-02-15
 */
@RestController
@RequestMapping("/redis")
@Api(tags = "redis工具类测试接口")
@Slf4j
public class RedisTestController {

    @Autowired
    private IDemo1SchedulerJobService demo1SchedulerJobService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis以对象json字符串保存(推荐)
     */
    @GetMapping("/saveObjectString")
    @ApiOperation(value = "redis以对象字符串保存")
    public void saveObjectString() {
        try {
            Demo1SchedulerJob anjuke_job = demo1SchedulerJobService.getById("anjuke_job");
            String jobString = JSONObject.toJSONString(anjuke_job);
            RedisUtil.StringOps.setEx("anjuke_job", jobString, 2, TimeUnit.MINUTES);
            String s = RedisUtil.StringOps.get("anjuke_job");
            Demo1SchedulerJob demo1SchedulerJob = JSONObject.parseObject(s, Demo1SchedulerJob.class);
            log.info(demo1SchedulerJob.getJobId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * redis以对象默认序列化保存
     */
    @GetMapping("/saveObjectSerializable")
    @ApiOperation(value = "redis以对象默认序列化保存")
    public void saveObjectSerializable() {
        try {
            Demo1SchedulerJob anjuke_job = demo1SchedulerJobService.getById("anjuke_job");
            // 工具类未封装对象序列化保存方法，此处使用原生redisTemplate
            redisTemplate.opsForValue().set("anjuke_job",anjuke_job);
            Object object = redisTemplate.opsForValue().get("anjuke_job");
            if(object instanceof Demo1SchedulerJob){
                Demo1SchedulerJob demo1SchedulerJob = (Demo1SchedulerJob) object;
                log.info(demo1SchedulerJob.getJobId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
